<template>
	<div id="lineAndPoly">
		<a-tree
             v-model:checkedKeys="checkedKeys"
			:show-line="showLine"
			:show-icon="showIcon"
			:defaultExpandAll="true"
			:tree-data="treeList"
			checkable
			@select="onSelect"
            @check="onCheck"
		>
			<!-- <template #icon>
				<FileSyncOutlined />
			</template> -->
			<template #title="{ dataRef }">
				<template v-if="dataRef.key === '0-0-0-1'">
					<div>multiple line title</div>
					<div>multiple line title</div>
				</template>
				<template v-else>{{ dataRef.title }}</template>
			</template>
			<template #switcherIcon="{ dataRef, defaultIcon }">
                
				<FileSyncOutlined v-if="dataRef.key == '0-01'" />
				<component :is="defaultIcon" v-else />
			</template>
		</a-tree>
	</div>
</template>
<script setup>
import { ref, reactive, defineProps, watch, onMounted, watchEffect,nextTick } from 'vue';
import {customborder,customborder3} from '../views/mapBorder'
import {banline1, banline2} from '../views/mapLines'
import { api_get } from '../untils/common.js'
import dayjs from 'dayjs';
import {
	saveItem,
	getItems,
	getItemById,
	updateItem,
	deleteItem,
} from '../db';
const showLine = ref(true);
const showIcon = ref(true);

const props = defineProps({
	overlays: Object,
	updateOverlays: Function,
	updateList: String,
	updateAmenuTopList: Function,
	catMap: Object,
});
// watch(() => props.overlays,async (newValue) => {
//     props.overlays.value = newValue
// });
watch(()=>props.updateList,(newValue)=>{
	updateTreeList()
})

//   如果没有固定的假数据， saveItem 它， 因为用在ant数，form的表单数据为默认值

const formDataByDBList = ref(null);
const treeList = ref([
	{
		title: '线路预警围栏',
		key: '0-0',
        maptype:'Overlay.Polyline',
		children: [],
	},
	{
		title: '行政区域围栏',
		key: '0-1',
        maptype:'Overlay.Polygon',
		children: [],
	},
	{
		title: '多边形电子围栏',
        maptype:'Overlay.Rectangle',
		key: '0-2',
		children: [],
	},
]);


const expandedKeys = ref([7788, 8888]);
const checkedKeys = ref([]);



watch(checkedKeys, (e,a) => {
    console.log(props.overlays,'xx');
	console.log('checkedKeys', checkedKeys,a);
});

/**getItems()
 * 
{
    "userName": "管理员",
    "byShare": false,
    "byDependency": true,
    "bymanor": false,
    "byTime": false,
    "limitSpeed": false,
    "originGpsCoord": false,
    "areaType": "polygon",
    "maxSpeed": "90.0",
    "startDate": "2024-08-01 00:00:00",
    "endDate": "2024-08-27 09:19:51",
    "epidemicRisk": "",
    "delay": 10,
    "glv": 20,
    "date": [
        "2024-07-31T16:00:00.000Z",
        "2024-08-27T01:19:51.294Z"
    ],
    "adname": "",
    "name": "多边形1",
    "txnr": "你已进入石景山咯咯咯",
    "points": "107.166331,38.285602;107.265699,38.083831;106.962075,38.107726;106.865468,38.19238;106.923432,38.300767",
    "alarmTypes1s": "",
    "alarmTypes2s": "",
    "alarmType": "进区域报警给驾驶员，进区域报警给平台，",
    "type": "",
    "checkedList1": [
        "进区域报警给驾驶员",
        "进区域报警给平台"
    ],
    "checkedList2": [],
    "approver": "",
    "dateTime": null,
    "description": "",
    "createDate": "2024-08-27 09:21:03",
    "id": 7790
}
getItems()
 */

 
import getMarkerList from '../static/localData/getMarkerList.json'
 
const updateTreeList = async ()=> {
        formDataByDBList.value = await getItems()
        formDataByDBList.value.push(...await getItems('govLine'))

        getMarkerList.data.map(item=>{
            const formattedCoordinates = item.Longtude.map((longitude, index) => {
                return `${longitude},${item.Latitude[index]}`;
            }).join(';');
            
            item.points = formattedCoordinates
            item.areaType = 'polygon'
            item.name = item.Name
            item.id = item.Id + '_Id'
            item['fixedPolygon'] = true
        })
        formDataByDBList.value.push(...getMarkerList.data)
        
        setTimeout(() => {
            treeList.value[2]['children'] = formDataByDBList.value
                .filter((item) => item.areaType == 'polygon')
                .map((item) => {
                    return {
                        title: item.name,
                        key: item.key?item.key:item.id,
                        maptype:'Overlay.Polygon'
                    };
                });
            
            treeList.value[1]['children'] = formDataByDBList.value
                .filter((item) => item.areaType == 'govArea') // 过滤掉不符合条件的项
                .map((item) => {
                    return {
                        title: item.name,
                        key: item.key?item.key:item.id,
                        disableCheckbox: item.key == 7789?false:false,
                        maptype:'Overlay.Rectangle'
                    };
                });
    
            treeList.value[0]['children'] = formDataByDBList.value
                .filter((item) => item.areaType == 'govLine')
                .map((item) => {
                    return {
                        title: item.name,
                        key: item.key?item.key:item.id,
                        maptype:'Overlay.Polyline'
                    };
                });
    
                checkedKeys.value.push(7788)
                checkedKeys.value.push(7789)
                checkedKeys.value.push(8888)
                checkedKeys.value.push(8889)
        }, 100);

        console.log(treeList.value, 'treeList');
        
    }

onMounted(async () => {
	formDataByDBList.value = await getItems();
	
    addPolygon(customborder,'', 7788);
    addPolygon(customborder3,'', 7789);
    addPolyline(banline1,'', 8888);
    addPolyline(banline2,'', 8889);
    
    nextTick( ()=>{
        setTimeout(() => {
            updateTreeList()
            props.updateAmenuTopList()
        }, 500);
    })

});
// 获取getItem 数据后对数据处理成ant树数据格式


const onSelect = (selectedKeys, info) => {
	console.log('selected', selectedKeys, info);
};

// 根据选中节点显示或隐藏覆盖物
// 当前添加覆盖物的列表中如果它们的key和复选框数据key一致, 进行显示隐藏

const onCheck = (checkedKeys, checked) => {
    let checkedEventKey =  checked.node.eventKey
    let checkedNode =  checked.node.eventKey
    Object.keys(props.overlays).forEach(key => {
        // if (typeof key == 'string') key = key*1
        if (checkedKeys.includes(key)) {
            if (props.overlays[key]) {
                props.overlays[key].show();
            }
        } else {
            console.log(props.overlays);
            console.log(props.overlays[key]);

            if ((props.overlays[key] && props.overlays[key].getExtData().fixedWeilan)) {
                props.overlays[key].hide()
            }
        }
    });

    
    if (!props.overlays[checkedEventKey]) {
        let checkedNodeData = formDataByDBList.value.filter(item=>item.id==checkedNode)
        if (checkedNodeData.length==0 && (checked.node.children && checked.node.children.length)) {
            checked.node.children.forEach(node=>{

                if (props.overlays[node.key]) return;
                
                checkedNodeData = formDataByDBList.value.filter(item=>item.id==node.key)[0]
                
                let lnglats = checkedNodeData.points.split(';')
                let path = lnglats.map(lnglat=>{
                    return lnglat.split(',')
                })
                if (checkedNodeData.areaType == 'govArea' || checkedNodeData.areaType == 'polygon') {
                    addPolygon(path,checkedNodeData['name'], node.key);
                }
            })
            return
        }

        checkedNodeData = checkedNodeData ? checkedNodeData[0] : []
        let lnglats = checkedNodeData.points.split(';')
        let path = lnglats.map(lnglat=>{
            return lnglat.split(',')
        })
        if (checkedNodeData.areaType == 'govArea' || checkedNodeData.areaType == 'polygon') {
            addPolygon(path,checkedNodeData['name'], checkedEventKey, checkedNodeData.areaType , checkedNodeData.fixedPolygon);
        }
    }
    
    let paddings = [160, 200, 400, 400].map(val => val *= .9)
    if (checked.checked && props.overlays[checkedEventKey]) {
        props.catMap.setFitView(props.overlays[checkedEventKey], false, paddings);
    }
    
};


let zIndexAddNum = 1


function addPolyline(path, where = '', key) {
    var polyline = new AMap.Polyline({
        path: path,
        isOutline: true,
        outlineColor: 'transparent',
        borderWeight: 3,
        strokeColor: "#e52b1d",
        strokeOpacity: 1,
        strokeWeight: 3,
        // 折线样式还支持 'dashed'
        strokeStyle: "solid",
        // strokeStyle是dashed时有效
        strokeDasharray: [5, 5],
        lineJoin: 'round',
        lineCap: 'round',
        extData: {
            weilan: true
        }
    })
    var text = new AMap.Text({
        text: where + "禁行路线", //标记显示的文本内容
        anchor: "center", //设置文本标记锚点位置
        draggable: true, //是否可拖拽
        cursor: "pointer", //指定鼠标悬停时的鼠标样式。
        angle: -2, //点标记的旋转角度
        style: {
            //设置文本样式，Object 同 css 样式表
            "padding": "0.15rem .35rem",
            "margin-bottom": "1rem",
            "border-radius": "0.25rem",
            "background-color": "rgb(21 40 91 / 58%)",
            "border-width": "0px",
            "text-align": "center",
            "font-size": "12px",
        },


        position: [path[0][0], path[0][1]], //点标记在地图上显示的位置
    });
    polyline.on('mouseover', () => {

        text.setMap(props.catMap);
    })
    polyline.on('mouseout', () => {
        props.catMap.remove(text)
    })
    props.catMap.add(polyline);
    props.overlays[key] = polyline
    DBAddItem(key, key, path, 'govLine')
    // props.catMap.setFitView();
}

function addPolygon(path, where='', key, areaType='govArea', fixedPolygon=false) {
    // 使用map和forEach来遍历并修改每个坐标  
    path = path.map(coordinates => {  
        return coordinates.map(coordinate => parseFloat((coordinate*1).toFixed(6)));  
    });  
    let layData = {
        path: path,
        fillColor: 'darkred',
        strokeOpacity: 1,
        fillOpacity: 0.5,
        strokeColor: 'blue',
        strokeWeight: 1,
        strokeStyle: 'dashed',
        strokeDasharray: [5, 5],
        zIndex: 50 + zIndexAddNum,
    }
    if (key == 7789) {
        layData = {
            strokeColor: '#04385f',
            strokeWeight: 2,
            fillOpacity: .3,
            fillColor: '#1791fc',
            zIndex:49
        }
        layData.path = path
    }
    layData.extData = {
        weilan: true
    }

    if (fixedPolygon) {
        layData.extData = {
            fixedWeilan: true
        }   
    }
    
    let polygon
    if (!props.overlays[key]) {
        polygon = new AMap.Polygon(layData);
    } else {
        polygon = props.overlays[key]
    }
    
    zIndexAddNum++
    //   text.setMap(catMap); //将文本标记设置到地图上
    let bounds = polygon.getBounds()
    let lng = bounds['northEast']?bounds['northEast'].lng:bounds['northeast']?bounds['northeast'].lng:''
    let lat = bounds['northEast']?bounds['northEast'].lat:bounds['northeast']?bounds['northeast'].lat:''
    var text = new AMap.Text({
        text: where + "禁行区域", //标记显示的文本内容
        anchor: "center", //设置文本标记锚点位置
        draggable: true, //是否可拖拽
        cursor: "pointer", //指定鼠标悬停时的鼠标样式。
        angle: -2, //点标记的旋转角度
        style: {
            //设置文本样式，Object 同 css 样式表
            "padding": "0.15rem .35rem",
            "margin-bottom": "1rem",
            "border-radius": "0.25rem",
            "background-color": "rgb(21 40 91 / 58%)",
            "border-width": "0px",
            "text-align": "center",
            "font-size": "12px",
        },
        
        position: [lng, lat], //点标记在地图上显示的位置
    });
    
    if (key != 7789) {

        polygon.on('mouseover', () => {
            text.setMap(props.catMap);
            polygon.setOptions({
                fillOpacity: 0.7,
                fillColor: 'blue'
            })
        })
        polygon.on('mouseout', () => {
            props.catMap.remove(text)
            polygon.setOptions({
                fillOpacity: 0.5,
                fillColor: 'red'

            })
        })
    }
    if (!props.overlays[key]) {
        props.overlays[key] = polygon
        props.catMap.add(polygon);
        let areaName = key
        if (key == 7789) {
            areaName ='宁东镇'
        }
        if (!fixedPolygon) DBAddItem(areaName, key, path, areaType)
    } else {
        polygon.show()
    }

}


async function DBAddItem(name, key, path, areaType){
    if (Array.isArray(path)) {
        path = path.join(';')
    }
    let FormData = {
        name,
        key,
        id: key,
        userName: '管理员',
        byShare: true,
        byDependency: true,
        bymanor: true,
        byTime: true,
        limitSpeed: true,
        originGpsCoord: true,
        areaType,
        maxSpeed: "90.0",
        startDate: '',
        endDate: '',
        epidemicRisk: '低风险',
        delay: 10,
        glv: 20,
        date: [
            dayjs().startOf('month'),
            dayjs()
        ],
        adname: '',
        txnr: '',
        points: path,
        alarmTypes1s: '',
        alarmTypes2s: '',
        alarmType: '',
        type: '',
        checkedList1: ['进区域报警给驾驶员', '进区域报警给平台'],
        checkedList2: ['进区域报警给驾驶员', '进区域报警给平台'],
        approver: '',
        dateTime: null,
        description: '',
    }
    
    var formInitData = reactive(FormData);
    let rs = await getItemById(areaType, key)
    if (!rs) {
        await saveItem(areaType, formInitData)
    }
}
</script>
<style>
/* .ant-tree-switcher-line-icon {
    display: none;
} */
.ant-tree-switcher-noop span svg {
    display: none;
}
.ant-tree-switcher-noop  {
    display: flex;
    align-items: center;
}
.ant-tree-switcher-noop span {
    width: 20px;
    height: 20px;
    background: url(../assets/treeicon.png);
    background-size: cover;
    background-size: 16px 16px;
    background-position: bottom;
    background-repeat: no-repeat;
}
.ant-tree-switcher-noop span::after {
    content:'1',
}
#lineAndPoly .ant-tree-checkbox:not(.ant-tree-checkbox-disabled) .ant-tree-checkbox-inner {
	background-color: transparent;
	opacity: 0.65;
}

.ant-tree .ant-tree-checkbox:not(.ant-tree-checkbox-disabled) .ant-tree-checkbox-inner {
	border-color: #d9d9d98a;
}

.ant-tabs .ant-tabs-tabpane {
    overflow: auto;
}
</style>
